<?php if (!defined('BASEPATH'))exit('No direct script access allowed');

class User extends MY_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('account_model');
        $this->load->model('finance_list_model');
        $this->load->model('experience_list_model');
        $this->load->model('withdraw_order_model');
        $this->load->model('withdraw_list_model');
        $this->load->model('exchange_order_model');
        $this->load->model('exchange_list_model');
        $this->load->model('users_spread_model');
        $this->load->model('plat_award_list_model');
        $this->load->model('plat_model');
        $this->load->model('users_log_model');
        $this->load->model('users_bank_model');
        $this->load->model('users_award_notice_model');
        $this->load->model('content_model');
        $this->load->model('cate_model');
        $this->load->model('new_task_model');
        $this->load->model('../../Application/models/task_model');
        $this->is_login();
        $query_params = "user_id,nickname,head_img,sex,signature";
        $user_info = $this->db->query("select $query_params from tan_users_info where user_id = ".$this->user_id." order by id desc limit 1")->row_array();
        $user_info['signature'] = $user_info['signature'] ? $user_info['signature'] : "这个人好懒，什么也没有写～";

        $user_info['head_img'] = strstr($user_info['head_img'],"http") ? $user_info['head_img'] : $this->img_host.$user_info['head_img'];
        //账户信息
        $user_account = $this->db->query("select a.balance finance_balance,b.balance zhu_balance from tan_account a left join tan_bbs_account b on b.user_id = a.user_id where a.user_id = ".$this->user_id." order by a.id desc limit 1")->row_array();;
        $user_info['account'] = $user_account;
        //统计信息
        $user_count = $this->db->query("select * from tan_bbs_count where user_id = ".$this->user_id." order by id desc limit 1")->row_array();
        $user_count['articles_count'] = $this->db->query("select * from tan_bbs_article where authorid = ".$this->user_id." and  status = 1 order by id desc")->num_rows();
        $user_count['reply_count'] = $this->db->query("select * from tan_bbs_article_comment where uid = ".$this->user_id." and  is_show = 1 order by id desc")->num_rows();
        $user_info['bbs_count'] = $user_count;
        $this->zhu_balace = $user_account['zhu_balance'];
        //获取users表的数据
        $tan_users = $this->db->query("select * from tan_users where user_id = ".$this->user_id.".limit 1")->row_array();
        $user_info['paypassword'] = $tan_users['paypassword'];
        $user_info['salt'] = $tan_users['salt'];
        $this->userinfo['user_id'] = $tan_users['user_id'];
        $this->user_info = $user_info;
    }
    //体现绑定页面
    function cash_bind(){

        $this->session->set_userdata("sms_code",null);
        $where = array();
        if(isset($_GET['id'])){
            $where['id'] = $_GET['id'];
            $bind_info = $this->users_bank_model->get($where);
            $this->assign("bind_info", $bind_info);
        }
        if ($_GET['type']==1){
            $this->display('user/cash_bind_alipay.html');
        }else if ($_GET['type']==2){
            $this->display('user/cash_bind_bank.html');
        }

    }

    //申请体现页面
    function cash(){

        $this->session->set_userdata("sms_code",null);
        //账号余额
        $balance_liubi = floor($this->user_info['account']['finance_balance']);
        $balance = intval($balance_liubi/10000);
        $withdraw_min_alipay = $this->config_award['withdraw_min_alipay'];//支付宝提现最低额度
        $withdraw_min_bank = $this->config_award['withdraw_min_bank'];//银行卡提现最低额度

        $where = array();
        $where['user_id'] = $this->userinfo['user_id'];
        $where['type'] = 1;//支付宝
        $alipay = $this->users_bank_model->get_list($where,0,10);
        //var_dump($alipay);exit();
        //echo $this->db->last_query();exit();
        $where['type'] = 2;
        $bank = $this->users_bank_model->get_list($where,0,10);
        $this->assign('withdraw_min_alipay', $withdraw_min_alipay);
        $this->assign('withdraw_min_bank', $withdraw_min_bank);
        $this->assign('liubi_balance', intval($balance_liubi));
        $this->assign('balance', $balance);
        $this->assign("alipay_flag",$balance > $withdraw_min_alipay ? 1 : 0 );
        $this->assign("bank_flag",$balance > $withdraw_min_bank ? 1 : 0 );


        //社区溜珠
        $liuzhu_balance = $this->user_info['account']['zhu_balance'];
        //$this->user_info['account']['zhu_balance']
        $liuzhu_balance = intval($liuzhu_balance);
        $this->assign("liuzhu_alipay_flag",$liuzhu_balance > $withdraw_min_alipay ? 1 : 0 );
        $this->assign("liuzhu_bank_flag",$liuzhu_balance > $withdraw_min_bank ? 1 : 0 );
        $this->assign('liuzhu_balance', $liuzhu_balance);

        $this->assign("alipays", $alipay);
        $this->assign("banks", $bank);

        //VIP
        $next_vip = $this->config_vip[$this->user_info['vip_degree']+1];
        $this->assign('next_vip', $next_vip);
        if ($_GET['type']==1){
            $this->display('user/cash_b.html');
        }else if($_GET['type']==2){
            $this->display('user/cash_z.html');
        }
    }

    //绑定支付宝
    function bind_alipay(){

        if($_POST){
            $name = trim($_POST['Name']);
            $account = trim($_POST['Account']);
            $where['user_id'] = $this->userinfo['user_id'];
            $where['type'] = 1;//支付宝
            $alipay_list = $this->users_bank_model->get_list($where);
            if(count($alipay_list) >= 2){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "绑定账户数最多2个，您已达上限";
                echo JSON($mess);exit;
            }
            $data = array();
            $data['user_id'] = $this->userinfo['user_id'];
            $data['name'] = $name;
            $data['account'] = $account;
            $data['type'] = 1;
            $data['create_time'] = time();
            $result = $this->users_bank_model->insert($data);
            if($result){
                //写入日志
                $log_data = array();
                $log_data['user_id'] = $this->userinfo['user_id'];
                $log_data['events'] = 'binding';
                $log_data['content'] = '绑定支付宝成功'.$name.$account;
                $log_data['ip'] = $this->input->ip_address();
                $log_data['create_time'] = time();
                $this->users_log_model->insert($log_data);

                $where = array();
                $where['user_id'] = $this->userinfo['user_id'];
                $where['type'] = 1;//支付宝
                $alipay_list = $this->users_bank_model->get_list($where);
                $str = "<tr><th>姓名</th><th>支付宝账号</th><th>操作</th></tr>";
                foreach ($alipay_list as $key=>$val){
                    $str .= "<tr><td>".$val['name']."</td><td>".$val['account']."</td><td class='delete-bind'><a href='javascript:void(0);' data-id='".$val['id']."'  data-type='1'>删除</a></td></tr>";
                }
                $this->session->set_userdata("sms_code",null);
                $mess['reqStatus'] = true;
                $mess['errorMsg'] = "绑定成功";
                $mess['data'] = $str;

                echo json_encode($mess);exit;
            }else{
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "绑定失败";
                echo JSON($mess);exit;
            }
        }else{
            $mess['reqStatus'] = false;
            $mess['errorCode'] = 1004;
            $mess['errorMsg'] = "非法访问";
            echo JSON($mess);exit;
        }
    }

    //绑定银行
    function bind_bank(){
        if($_POST){
            $name = trim($_POST['Name']);
            $account = trim($_POST['Account']);
            $bank_type = trim($_POST['bankType']);
            $bank_home = trim($_POST['bankHome']);

            $where['user_id'] = $this->userinfo['user_id'];
            $where['type'] = 2;//银行卡
            $bank_list = $this->users_bank_model->get_list($where);
            if(count($bank_list) >= 2){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "绑定账户数最多2个，您已达上限";
                echo JSON($mess);exit;
            }

            $data = array();
            $data['user_id'] = $this->userinfo['user_id'];
            $data['name'] = $name;
            $data['account'] = $account;
            $data['bank_type'] = $bank_type;
            $data['bank_home'] = $bank_home;
            $data['type'] = 2;
            $data['create_time'] = time();
            $result = $this->users_bank_model->insert($data);
            if($result){
                //写入日志
                $log_data = array();
                $log_data['user_id'] = $this->userinfo['user_id'];
                $log_data['events'] = 'binding';
                $log_data['content'] = '绑定银行卡成功'.$name.$account.$bank_home;
                $log_data['ip'] = $this->input->ip_address();
                $log_data['create_time'] = time();
                $this->users_log_model->insert($log_data);

                $where = array();
                $where['user_id'] = $this->userinfo['user_id'];
                $where['type'] = 2;//银行卡
                $alipay_list = $this->users_bank_model->get_list($where);
                $str = "<tr><th>姓名</th><th>卡号</th><th>银行类型</th><th>操作</th></tr>";
                foreach ($alipay_list as $key=>$val){
                    $str .= "<tr><td>".$val['name']."</td><td>".$val['account']."</td><td>".$val['bank_type']."</td><td class='delete-bind'><a href='javascript:void(0);' data-id='".$val['id']."' data-type='1'>删除</a></td></tr>";
                }
                $this->session->set_userdata("sms_code",null);
                $mess['reqStatus'] = true;
                $mess['errorMsg'] = "绑定成功";
                $mess['data'] = $str;

                echo json_encode($mess);exit;
            }else{
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "绑定失败";
                echo JSON($mess);exit;
            }
        }else{
            $mess['reqStatus'] = false;
            $mess['errorCode'] = 1004;
            $mess['errorMsg'] = "非法访问";
            echo JSON($mess);exit;
        }
    }

    //体现
    function do_cash(){
        //账号余额
        $balance = floor($this->user_info['account']['finance_balance']);
        $balance = intval($balance/10000);
        $withdraw_min_alipay = $this->config_award['withdraw_min_alipay'];//支付宝提现最低额度
        $withdraw_min_bank = $this->config_award['withdraw_min_bank'];//银行卡提现最低额度
        if($_POST){
            $mess = array();
            $type = trim($_POST['type']);//提现方式
            $accountId = trim($_POST['accountId']);//提现账户
            $payPass = trim($_POST['payPass']);//交易密码
            $cashValue = trim($_POST['cashValue']);//提现金额

            $SSID = isset($_POST['keyCode']) ? trim($_POST['keyCode']) : "";
            if($SSID != $this->session_id){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1001;
                $mess['errorMsg'] = "访问超时，请重新登录";
                echo JSON($mess);exit;
            }


            if(!$type && $type != 1 && $type != 2){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "请选择提现方式";
                echo JSON($mess);exit;
            }
            $bank = $this->users_bank_model->get(array('user_id'=>$this->userinfo['user_id'],'id'=>$accountId));
            if(!$bank){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "请选择提现账号";
                echo JSON($mess);exit;
            }
            //是否大于余额
            if($cashValue > $balance){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "溜溜币不足，无法提现哦";
                echo JSON($mess);exit;
            }
            if($type == 1 && $cashValue < $withdraw_min_alipay){//支付宝
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "支付宝最低提现<i style='color:red;'>$withdraw_min_alipay</i>元";
                echo JSON($mess);exit;
            }

            if($type == 2 && $cashValue < $withdraw_min_bank){//银行卡
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "银行卡最低提现<i style='color:red;'>$withdraw_min_bank</i>元";
                echo JSON($mess);exit;
            }
            //提现金额小于20，扣除0.5手续费
            if($cashValue < 20){
                $fee = $this->config_award['withdraw_fee'];
            }else{
                $fee = 0.0;
            }
            $amount = intval($cashValue)*10000;
            $type_tile = $type == 1 ? "支付宝" : "银行卡";
            //检测交易密码
            //echo $this->user_info['paypassword'] ;exit();
            if($this->user_info['paypassword'] != md5(md5($payPass) .$this->user_info['salt'])){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "请输入正确的交易密码";
                echo JSON($mess);exit;
            }
            //处理提现订单MakeOrdId
            $cash_order = array();
            $cash_order['user_id'] = $this->userinfo['user_id'];
            $cash_order['order_nid'] = MakeOrdId($this->userinfo['user_id']);
            $cash_order['amount'] = $cashValue;
            $cash_order['fee'] = $fee;
            $cash_order['true_amount'] = $cashValue - $fee;
            $cash_order['account'] = $bank['account'];
            $cash_order['name'] = $bank['name'];
            $cash_order['bank_type'] = $bank['bank_type'];
            $cash_order['bank_home'] = $bank['bank_home'];
            $cash_order['type'] = $type;
            $cash_order['status'] = 2;
            $cash_order['create_time'] = time();
            $result = $this->withdraw_order_model->insert($cash_order);
            if($result){//申请成功
                //获取用户账户信息
                $account = $this->account_model->get($this->userinfo['user_id']);
                $account_data = array();
                $account_data['balance'] = $account['balance'] - $amount;//账户余额
                $account_data['expend'] = $account['expend'] + $amount;//总支出
                //更新账户
                $this->account_model->update($account_data,$this->userinfo['user_id']);
                //生成提现记录
                $withdraw_data = array();
                $withdraw_data['user_id'] = $cash_order['user_id'];
                $withdraw_data['order_nid'] = $cash_order['order_nid'];
                $withdraw_data['amount'] = $cash_order['amount'];
                $withdraw_data['fee'] = $cash_order['fee'];
                $withdraw_data['finance'] = $amount;
                $withdraw_data['status'] = $cash_order['status'];
                $withdraw_data['create_time'] = time();
                $withdraw_data['account'] = $cash_order['account'];
                $withdraw_data['truename'] = $cash_order['name'];
                $this->withdraw_list_model->insert($withdraw_data);
                //溜溜币明细
                $finance_list_data = array();
                $finance_list_data['user_id'] = $this->userinfo['user_id'];
                $finance_list_data['content'] = $type_tile."提现".$cashValue."元";
                $finance_list_data['finance'] = $amount;
                $finance_list_data['finance_balance'] = $account_data['balance'];
                $finance_list_data['reward_type'] = 'withdraw_deduct';
                $finance_list_data['type'] = 2;
                $finance_list_data['create_time'] = time();
                $finance_list_data['month'] = date("Ym");
                $finance_list_data['day'] = date("Ymd");
                $this->finance_list_model->insert($finance_list_data);

                //日志
                $log_data = array();
                $log_data['user_id'] = $this->userinfo['user_id'];
                $log_data['events'] = 'withdraw';
                $log_data['content'] = '申请提现';
                $log_data['ip'] = $this->input->ip_address();
                $log_data['create_time'] = time();
                $this->users_log_model->insert($log_data);

                $mess['reqStatus'] = true;
                $mess['errorCode'] = 0;
                echo JSON($mess);exit;
            }else{
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "提现失败";
            }
        }else{
            $mess['reqStatus'] = false;
            $mess['errorCode'] = 1004;
            $mess['errorMsg'] = "非法访问";
            echo JSON($mess);exit;
        }
    }

    //溜珠提现
    function do_lzcash(){
        //账号余额
        //$balance = floor($this->user_info['bbs_account']['balance']);
        $balance = floor($this->user_info['account']['zhu_balance']);
        $withdraw_min_alipay = $this->config_award['withdraw_min_alipay'];//支付宝提现最低额度
        $withdraw_min_bank = $this->config_award['withdraw_min_bank'];//银行卡提现最低额度
        if($_POST){
            $mess = array();
            $type = trim($_POST['type']);//提现方式
            $accountId = trim($_POST['accountId']);//提现账户
            $payPass = trim($_POST['payPass']);//交易密码
            $cashValue = trim($_POST['cashValue']);//提现金额

            $SSID = isset($_POST['keyCode']) ? trim($_POST['keyCode']) : "";
            if($SSID != $this->session_id){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1001;
                $mess['errorMsg'] = "访问超时，请重新登录";
                echo JSON($mess);exit;
            }

            if(!$type && $type != 1 && $type != 2){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "请选择提现方式";
                echo JSON($mess);exit;
            }
            $bank = $this->users_bank_model->get(array('user_id'=>$this->userinfo['user_id'],'id'=>$accountId));
            if(!$bank){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "请选择提现账号";
                echo JSON($mess);exit;
            }
            //是否大于余额
            if($cashValue > $balance){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "溜溜币不足，无法提现哦";
                echo JSON($mess);exit;
            }
            if($type == 1 && $cashValue < $withdraw_min_alipay){//支付宝
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "支付宝最低提现<i style='color:red;'>$withdraw_min_alipay</i>元";
                echo JSON($mess);exit;
            }

            if($type == 2 && $cashValue < $withdraw_min_bank){//银行卡
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "银行卡最低提现<i style='color:red;'>$withdraw_min_bank</i>元";
                echo JSON($mess);exit;
            }
            $amount = 0;
            //检测交易密码

            if($this->user_info['paypassword'] != md5(md5($payPass) .$this->user_info['salt'])){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "请输入正确的交易密码";
                echo JSON($mess);exit;
            }
            //处理提现订单MakeOrdId
            $cash_order = array();
            $cash_order['user_id'] = $this->userinfo['user_id'];
            $cash_order['order_nid'] = MakeOrdId($this->userinfo['user_id']);
            $cash_order['amount'] = $cashValue;
            $cash_order['fee'] = 0;
            $cash_order['true_amount'] = $cashValue;
            $cash_order['account'] = $bank['account'];
            $cash_order['name'] = $bank['name'];
            $cash_order['bank_type'] = $bank['bank_type'];
            $cash_order['bank_home'] = $bank['bank_home'];
            $cash_order['type'] = $type;
            $cash_order['without_type'] = 2;//溜珠提现
            $cash_order['status'] = 2;
            $cash_order['create_time'] = time();
            $result = $this->withdraw_order_model->insert($cash_order);
            if($result){//申请成功
                //获取用户账户信息
                $account = $this->db->query("select * from tan_bbs_account where user_id = ".$this->userinfo['user_id']." limit 1")->row_array();
                $account_data = array();
                $account_data['balance'] = $account['balance'] - intval($cashValue);//账户余额
                $account_data['expend'] = $account['expend'] + intval($cashValue);//总支出
                //更新账户
                $this->db->where(array("user_id"=>$this->userinfo['user_id']))->update("bbs_account",$account_data);
                //生成提现记录
                $withdraw_data = array();
                $withdraw_data['user_id'] = $cash_order['user_id'];
                $withdraw_data['order_nid'] = $cash_order['order_nid'];
                $withdraw_data['amount'] = $cash_order['amount'];
                $withdraw_data['fee'] = $cash_order['fee'];
                $withdraw_data['finance'] = $amount;
                $withdraw_data['status'] = $cash_order['status'];
                $withdraw_data['create_time'] = time();
                $withdraw_data['account'] = $cash_order['account'];
                $withdraw_data['truename'] = $cash_order['name'];
                $this->withdraw_list_model->insert($withdraw_data);

                //溜珠明细
                $this->db->insert("bbs_zhu_detail",array("user_id"=>$this->userinfo['user_id'],"num"=>intval($cashValue),"type"=>"提现","style"=>2,"create_time"=> time()));
                //日志
                $log_data = array();
                $log_data['user_id'] = $this->userinfo['user_id'];
                $log_data['events'] = 'withdraw';
                $log_data['content'] = '溜珠申请提现';
                $log_data['ip'] = $this->input->ip_address();
                $log_data['create_time'] = time();
                $this->users_log_model->insert($log_data);

                $mess['reqStatus'] = true;
                $mess['errorCode'] = 0;
                echo JSON($mess);exit;
            }else{
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "提现失败";
            }
        }else{
            $mess['reqStatus'] = false;
            $mess['errorCode'] = 1004;
            $mess['errorMsg'] = "非法访问";
            echo JSON($mess);exit;
        }
    }

    //通过type获得绑定银行卡或者
    function bind_list(){
        $where = array();
        $where['user_id'] = $this->userinfo['user_id'];
        $where['type'] = 1;//支付宝
        $alipay_list = $this->users_bank_model->get_list($where,0,10);
        $where['type'] = 2;//银行卡
        $bank_list = $this->users_bank_model->get_list($where,0,10);
        $this->assign("alipay_list", $alipay_list);
        $this->assign("bank_list", $bank_list);
        $this->assign("type", $_GET['type']);
        $this->display('user/bind_list.html');
    }

    //绑定支付宝，银行卡修改
    function bind_update(){

    }

    //绑定支付宝，银行卡删除
    function bind_delete(){
        $this->is_login();
        $id = $_GET['id'];
        if(empty($id)){
            $mess['reqStatus'] = true;
            $mess['errorCode'] = 1000;
            $mess['errorMsg'] = "请求参数错误";
            echo JSON($mess);exit;
        }
        $where = array('id'=>$id);
        $flag = $this->users_bank_model->delete($where);
        if($flag){
            $mess['reqStatus'] = true;
            $mess['errorCode'] = 1000;
            $mess['errorMsg'] = "删除成功";
            echo JSON($mess);exit;
        }else{
            $mess['reqStatus'] = true;
            $mess['errorCode'] = 1000;
            $mess['errorMsg'] = "删除失败";
            echo JSON($mess);exit;
        }
    }

    private function is_login(){
        if(!$this->user_id){
            $url = site_url("account/login").$this->get_next_request_url();
            header("Location:".$url);
            exit;
        }
    }

    //个人空间任务领取列表
    function taskrec(){
        if($_POST){
            $pageIndex = isset($_REQUEST['pageIndex']) ? trim($_REQUEST['pageIndex']) : 0;
            $type = isset($_REQUEST['type']) ? trim($_REQUEST['type']) : 0;
            $uuid = isset($_REQUEST['uuid']) ? trim($_REQUEST['uuid']) : 0;
            $uuid = decrypt_user_id($uuid);
            $records_per_page = 10;

            if($type == 1){//未提交
                $where = " and st.is_post = 0 ";
            }elseif($type == 2){//已提交
                $where = " and st.is_post = 1";
            }else{//全部
                $where = "and 1 = 1";
            }
            $web_config = $this->task_model->website_config();
            $totalCount = $this->db->query("select st.* from tan_subtasks st where st.uid = $uuid $where order by st.sid desc")->num_rows();
            $list = $this->db->query("select st.*,t.title,t.commission,t.commission_per,t.cate_id,t.redirect_url,t.count_url from tan_subtasks st left join tan_task t on t.tid=st.tid where st.uid = $uuid $where  order by st.sid desc limit ".($pageIndex * $records_per_page).",".$records_per_page)->result_array();
            $html = "";

            foreach ($list as $key => $val){
                $list[$key]['left_time'] = -1;
                $list[$key]['task_status'] = "";
                $list[$key]['rec_sta'] = "";
                $list[$key]['subtask_status'] = "";

                if ($val['is_end'] == 1) {
                    $list[$key]['subtask_status'] = "<span class='fr' style='color: green;font-size: 16px;height: 27px;overflow: hidden;'>成功</span>";
                }
                if ($val['is_end'] == 2) {
                    $list[$key]['subtask_status'] = "<span class='fr' style='color:red;font-size: 16px;height: 27px;overflow: hidden;'>失败</span>";
                }
                if ($val['cate_id']==4){
                    $list[$key]['task_url'] = site_url("task/" . encrypt_wenda_id($val['tid']));
                    if ($val['qualification']==1){
                        if ($val['apply_end']==1){
                            $list[$key]['task_status'] .= "&nbsp;<span class='green'>已申请结束</span>";
                            if ($val['is_end']==1){
                                $list[$key]['end_num'] = $val['end_num'];
                            }
                        }else{
                            $list[$key]['rec_sta'] .= "<a class='iconfont fr mr5' style='position:relative;width: auto;height: auto;' href='javascript:;' onclick=\"apply_finish(".encrypt_wenda_id($val['tid']).",".encrypt_wenda_id($val['sid']).")\"><span class='bj-red colfff' style='border-radius:3px;padding: 4px;color: #fff;'>申请结束</span></a>";
                            $list[$key]['task_status'] .= "&nbsp;<span class='green'>资质通过</span>";
                        }
                    }elseif ($val['qualification']==2){
                        $list[$key]['task_status'] .= "&nbsp;<span class='red'>资质未通过</span>";
                    }else{
                        $list[$key]['task_status'] .= "&nbsp;<span class='red'>资质未验证</span>";
                    }
                }else {

                    if ($val['is_post'] == 1) {
                        $list[$key]['task_status'] .= "<span class='green'>已提交</span>&nbsp;";
                        if ($val['status'] == 4) {
                            $list[$key]['task_status'] .= "<span class='error'>已取消</span>&nbsp;";
                        } elseif ($val['status'] == 2) {
                            //添加时间：配置有时间限制（60分钟），当前时间 - 审核时间
                            $task_promulgator_period = $web_config['task_promulgator_period'];//单位：小时
                            $time_dif = $task_promulgator_period * 3600 - (time() - $val['check_time']);
                            $left_time = $time_dif < 0 ? 0 : $time_dif;
                            $list[$key]['task_promulgator_period'] = $left_time;
                            $list[$key]['task_status'] .= "&nbsp;<span style='color: red'>未通过</span>";
                            $appeal_info = $this->db->query("select c.*,u.username as initiator from tan_complaint c left join tan_users u on u.user_id=c.uid where c.sid=" . $val['sid'])->row_array();
                            if ($appeal_info) {
                                $list[$key]['rec_sta'] .= "<a class='iconfont fr mr5' style='position:relative;width: auto;height: auto;' href='" . site_url("account/taskappeal") . "?sid=" . encrypt_wenda_id($val['sid']) . "'><span class='bj-red colfff' style='border-radius:3px;padding: 4px;'>申诉详情</span></a>";
                                switch ($appeal_info['status']) {
                                    case 0:
                                        $appeal_tx = "申诉中";
                                        break;
                                    case 1:
                                        $appeal_tx = "申诉未通过";
                                        break;
                                    case 2:
                                        $appeal_tx = "申诉成功";
                                        break;
                                    case 4:
                                        $appeal_tx = "取消申诉";
                                        break;
                                    case 5:
                                        $appeal_tx = "申诉失败";
                                        break;
                                    default:
                                        $appeal_tx = "";
                                        break;
                                }
                                $list[$key]['task_status'] .= "&nbsp;<span style='color: blue'>" . $appeal_tx . "</span>";
                            } else {
                                $list[$key]['task_status'] .= "&nbsp;<span style='color: red'>未申诉</span>";

                                if ($val['is_end'] != 2) {
                                    $list[$key]['rec_sta'] .= "<a class='iconfont fr mr5' style='position:relative;width: auto;height: auto;' href='" . site_url("account/taskappeal") . "?sid=" . encrypt_wenda_id($val['sid']) . "'><span class='bj-red colfff' style='border-radius:3px;padding: 4px;'>申&nbsp;&nbsp;诉</span></a>";
                                }
                            }


                        } elseif ($val['status'] == 1) {
                            $list[$key]['task_status'] .= "&nbsp;<span style='color: green'>已通过</span>";
                        } else {
                            $list[$key]['task_status'] .= "&nbsp;<span style='color: blue'>等待验证</span>";
                            $list[$key]['rec_sta'] .= "&nbsp;&nbsp;<a class='iconfont fr mr5' style='position:relative;width: auto;height: auto;' href='javascript:;'><span class='bj-red colfff' id='type_on' data-id='" . encrypt_wenda_id($val['tid']) . "' style='border-radius:3px;padding: 4px;'>取消任务</span></a>";
                            $list[$key]['rec_sta'] .= "&nbsp;&nbsp;<a class='iconfont fr mr5' style='position:relative;width: auto;height: auto;' href='" . site_url("task/" . encrypt_wenda_id($val['tid'])) . "'><span class='bj-red colfff' style='border-radius:3px;padding: 4px;'>修改认证</span></a>";
                        }

                    } elseif ($val['is_post'] == 0) {
                        if ($val['status'] == 4 && $val['is_end'] == 2) {
                            $list[$key]['task_status'] .= "<span class='error'>已取消</span>&nbsp;";
                        } else if ($val['status'] == 3 && $val['is_end'] == 2) {
                            $list[$key]['task_status'] .= "<span class='error'>超时失败</span>&nbsp;";
                        } else {
                            //未提交加倒计时
                            $time_dif = time() - $val['add_time'];
                            $left_time = (60 * 60 - $time_dif) < 0 ? 0 : 60 * 60 - $time_dif;
                            $list[$key]['left_time'] = $left_time;
                            $list[$key]['task_status'] .= "<span class='error'>未提交</span>&nbsp;";
                            $list[$key]['rec_sta'] .= "&nbsp;&nbsp;<a class='iconfont fr mr5' style='position:relative;width: auto;height: auto;' href='javascript:;'><span class='bj-red colfff' id='type_on' data-id='" . encrypt_wenda_id($val['tid']) . "' style='border-radius:3px;padding: 4px;'>取消任务</span></a>";
                            $list[$key]['rec_sta'] .= "&nbsp;&nbsp;<a class='iconfont fr mr5' style='position:relative;width: auto;height: auto;' href='" . site_url("task/" . encrypt_wenda_id($val['tid'])) . "'><span class='bj-blue colfff' style='border-radius:3px;padding: 4px;'>提交认证</span></a>";
                        }
                    }
                    $list[$key]['task_url'] = site_url("task/" . encrypt_wenda_id($val['tid']));

                    /* lht 2018/5/18 16:28 区间理财任务佣金 */
                    if ($val['cate_id'] == 3) {
                        $list[$key]['commission'] = round($val['commission_per'] * $val['investment_money']);
                    } else {
                        $list[$key]['commission'] = $val['commission'] / 10000;
                    }
                }
            }
            $this->assign("totalCount", $totalCount);
            $this->assign("pageIndex", $pageIndex);
            $this->assign("list", $list);
            //$this->display('user/bind_list.html');
            $result = array(
                "reqStatus" => true,
                "data" => array(
                    "totalCount" => $totalCount ? $totalCount : 0,
                    "pageIndex" => $pageIndex,
                    "list" => $list
                )
            );
            echo json_encode($result, JSON_HEX_TAG);
            die;
        }else{
            $this->display('user/task_list.html');
        }
    }

    //任务申诉
    function ajax_appealsub(){
        $tsid = isset($_REQUEST['tsid']) ? trim($_REQUEST['tsid']) : 0;
        $tsid = decrypt_wenda_id($tsid);
        $data['content_word'] = isset($_REQUEST['content_word']) ? trim($_REQUEST['content_word']) : '';

        $subtask_info =  $this->db->query("select * from tan_subtasks where sid=$tsid")->row_array();
        $appeal_info = $this->db->query("select c.*,u.username as initiator from tan_complaint c left join tan_users u on u.user_id=c.uid where c.sid=$tsid")->row_array();
        $this->db->trans_begin();

        if (!$appeal_info){
            $appeal_data['sid'] = $tsid;
            $appeal_data['uid'] = $subtask_info['uid'];
            $appeal_data['add_time'] = time();
            $appeal_data['com_sn'] = 'C'.date('YmdHis').rand(1000,9999);
            $this->db->insert('tan_complaint', $appeal_data);
            $appeal_id = $this->db->insert_id();
            //第一次申请
        }else{
            $appeal_id = $appeal_info['cid'];
        }
        $appeal_comm = $this->db->query("select * from tan_complaint_comm where uid=".$this->userinfo['user_id']." and cid=$appeal_id order by add_time desc limit 1")->row_array();
        if (time()-$appeal_comm['add_time']<10){
            $result = array(
                "reqStatus" => false,
                "meg"   => "您说话太快！请稍候",
            );
        }else{
            $data['cid'] = $appeal_id;
            $data['uid'] = $this->userinfo['user_id'];
            $data['add_time'] = time();

            $this->db->insert('tan_complaint_comm', $data);
            $res = $this->db->insert_id();

            if ($res){
                $this->db->trans_commit();
                $result = array(
                    "reqStatus" => true,
                    "meg"   => "提交成功",
                );
            }else{
                $this->db->trans_rollback();
                $result = array(
                    "reqStatus" => false,
                    "meg"   => "提交失败",
                );
            }
        }



        echo json_encode($result,JSON_HEX_TAG);die;

    }
    //申请客服介入
    function ajax_taskkefu(){
        $tscid = isset($_REQUEST['tscid']) ? trim($_REQUEST['tscid']) : 0;
        $tscid = decrypt_wenda_id($tscid);
        //通过tscid获取sid

        if ($tscid){
            $this->db->trans_begin();//开启事务

            $appdata['is_kefu'] = 1;
            $res = $this->db->where(array('cid'=>$tscid))->update('tan_complaint',$appdata);
            $complaint = $this->db->query("select * from tan_complaint where cid={$tscid}")->row_array();
            $sid = $complaint['sid'];

            if ($res){
                $this->db->trans_commit();//提交事务
                $result = array(
                    "reqStatus" => true,
                    "meg"   => "申请成功",
                );
                $log_content =  $this->task_model->log_content();
                $log_arr = array(
                    'type_id'=>$sid,
                    'uid'=>$this->user_info['user_id'],
                    'type' => 2,
                    'content'=>$log_content['apply_service'],
                    'add_time'=>time(),
                );
                $this->task_model->add_subtasks_log($log_arr);
            }else{
                $this->db->trans_rollback();//事务回滚
                $result = array(
                    "reqStatus" => false,
                    "meg"   => "申请失败，请稍候重试",
                );
            }
        }
        echo json_encode($result,JSON_HEX_TAG);die;
    }
    //取消申诉
    function ajax_cancelappeal(){
        $tsid = isset($_REQUEST['tsid']) ? trim($_REQUEST['tsid']) : 0;
        $tscid = isset($_REQUEST['tscid']) ? trim($_REQUEST['tscid']) : 0;
        $tsid = decrypt_wenda_id($tsid);
        $tscid = decrypt_wenda_id($tscid);
        if ($tsid && $tscid){
            $this->db->trans_begin();//开启事务
            $subdata['is_end'] = 2;
            $res1 = $this->db->where(array('sid'=>$tsid))->update('tan_subtasks',$subdata);
            $appdata['status'] = 4;
            $res2 = $this->db->where(array('cid'=>$tscid))->update('tan_complaint',$appdata);

            if ($res1 && $res2){
                $this->db->trans_commit();//提交事务
                $result = array(
                    "reqStatus" => true,
                    "meg"   => "取消成功",
                );
                $log_content =  $this->task_model->log_content();
                $log_arr = array(
                    'type_id'=>$tsid,
                    'uid'=>$this->user_info['user_id'],
                    'type' => 2,
                    'content'=>$log_content['cancel_subtask'],
                    'add_time'=>time(),
                );
                $this->task_model->add_subtasks_log($log_arr);
            }else{
                $this->db->trans_rollback();//事务回滚
                $result = array(
                    "reqStatus" => false,
                    "meg"   => "取消失败，请稍候重试",
                );
            }
        }

        echo json_encode($result,JSON_HEX_TAG);die;
    }

    //我领取的任务申诉
    function taskappeal(){
        //$this->task_top();
        $subid = isset($_GET['sid']) ? trim($_GET['sid']) : 0;
        $subid = decrypt_wenda_id($subid);
        $appeal_info = $this->db->query("select c.*,u.username as initiator from tan_complaint c left join tan_users u on u.user_id=c.uid where c.sid=$subid")->row_array();
        $subtask_info =  $this->db->query("select * from tan_subtasks where sid=$subid")->row_array();
        $web_config = $this->task_model->website_config();
        if ($appeal_info){

            $task_info =  $this->db->query("select t.*,u.username as publisher from tan_task t left join tan_users u on u.user_id=t.uid where t.tid=".$subtask_info['tid'])->row_array();
            $comm_info =  $this->db->query("select cc.*,u.username from tan_complaint_comm cc left join tan_users u on u.user_id=cc.uid where cc.cid=".$appeal_info['cid']." order by cc.id desc")->result_array();

            $task_info['detail_url'] = 'http://'.$_SERVER['HTTP_HOST']."/task/".$task_info['tid'].".html";

            $subtask_info['add_time'] = $subtask_info["add_time"]?date("Y-m-d H:i:s",$subtask_info["add_time"]):'';
            $subtask_info['receive_time'] = $subtask_info["receive_time"]?date("Y-m-d H:i:s",$subtask_info["receive_time"]):'';
            $subtask_info['check_time'] = $subtask_info["check_time"]?date("Y-m-d H:i:s",$subtask_info["check_time"]):'';

            switch ($appeal_info['status']){
                case 0:
                    $appeal_info['status_val'] = "<font color='#00f'>申诉中</font>";
                    break;
                case 1:
                    $appeal_info['status_val'] = "<font color='#f0f'>发布方拒绝申诉</font>";
                    //申请客服介入时间倒计时，当前时间减去拒绝时间（从申诉表获取）
                    $task_receiver_period = $web_config['task_receiver_period'];//单位：小时
                    $time_dif = $task_receiver_period*3600 - (time() - $appeal_info['check_time']);
                    $left_time = $time_dif < 0 ? 0 : $time_dif;
                    $appeal_info['task_receiver_period'] = $left_time;
                    break;
                case 2:
                    $appeal_info['status_val'] = "<font color='#4dab0e'>申诉成功</font>";
                    break;
                case 4:
                    $appeal_info['status_val'] = "<font color='#00f'>取消申诉</font>";
                    break;
                case 5:
                    $appeal_info['status_val'] = "<font color='#f00'>申诉失败</font>";
                    break;
            }

            foreach ($comm_info as $item=>$value){
                if ($value['username']==''){
                    $comm_info[$item]['username'] = "<i style='color:#4dab0e'>客服</i>";
                }
                if ($value['uid']==$appeal_info['uid']){
                    $comm_info[$item]['username'] = "<i style='color:#f00'>".$value['username']."</i>";
                }
                if ($value['uid']==$task_info['uid']){
                    $comm_info[$item]['username'] = "<i style='color:#00f'>".$value['username']."</i>";
                }
                $comm_info[$item]['add_time'] = $value["add_time"]?date("Y-m-d H:i:s",$value["add_time"]):'';
            }

            $this->assign('appeal_info',$appeal_info);
            $this->assign('subtask_info',$subtask_info);
            $this->assign('task_info',$task_info);
            $this->assign('comm_info',$comm_info);
            $this->assign('cid',encrypt_wenda_id($appeal_info['cid']));
        }

        $this->assign("tid", $subtask_info['tid']);
        $this->assign("sid", $_GET['sid']);
        $this->assign("action", "taskappeal");
        $this->assign("act", "taskrec");
        $this->display("user/task_appeal.html");
    }



}
